//index.js
//获取应用实例
const app = getApp();
const getDateList = require('../../utils/date.js');
const Format = require("../../utils/time.js");
const ConvertPinyin = require("../../utils/convertToPinyinUpper.js");
const wxApi = require('../../utils/wxApi');
const QQMapWX = require('../../utils/qqmap-wx.js');
const utc = require('../../utils/utc.js');
var toActivityDetails = false;
var getList = function(that, newDate) { // 活动列表
    app.getApi.getNsProducts("POST", {
        pageNumber: that.data.pageNumber,
        pageSize: 10,
        availableBuyTime: newDate,
        isNotEndNow: that.data.isNotEndNow,
        cityId: that.data.cityId,
        method: "opg.eventPromote.find"
    }).then(data => {
        var list = that.data.items;
        if (data.data.totalCount == 0) {
            that.setData({
                noData: true
            })
        }
        // if (data.data.code == 200 && data.data.errMsg == "request:ok") {
        for (let i = 0; i < data.data.result.length; i++) {
            let dates = data.data.result[i].startTimeStr;
            var testTime = Format.getMonth(parseInt(dates.substring(5, 7)), that.data.isChinese)
            let times = testTime + dates.substring(8, 10);
            data.data.result[i].startTimeStr = times
            list.push(data.data.result[i])
        }
        if (Math.ceil(data.data.totalCount / 10) == that.data.pageNumber) {
            that.setData({
                isAll: true
            })
        }
        that.setData({
            items: list,
            loadMore: false
        })
        wx.stopPullDownRefresh()
    })
}
Page({
    data: {
        indexs: 0,
        pageNumber: 1,
        isNotEndNow: 0,
        currentNavs: { name: "Party", list: app.globalData.navs },
        areaName: "",
        years: [],
        hidden: false, //没有更多
        loadMore: true, //是否显示加载更多
        isAll: false,
        items: [],
        isChinese: wx.getStorageSync("isChinese"),
        code: "",
        userInfo: {},
        cityName: "",
        cityId: "",
        country: "China",
        newCount: 0
    },
    //事件处理函数
    bindViewTap: function() {

    },

    onLoad: function() {
        var res = wx.getSystemInfoSync();
        this.setData({
            eventWidth: res.windowWidth - 77
        })
    },
    location() { //获取地址信息
        if (wx.getStorageSync("areaId") == '' && !wx.getStorageSync("areaId")) { //地址信息不存在 获取用户地址
            var that = this
            var distance = new QQMapWX({
                key: 'VTSBZ-E4ICU-FHMVM-4NCEY-YBYU2-YAFYY' // 必填
            });
            distance.reverseGeocoder({
                success: function(res) {
                    var d = new Date().getTimezoneOffset() / 60;
                    if (d == -8) {
                        that.setData({
                            country: ""
                        })
                    } else {
                        that.setData({
                            country: ""
                        })
                    }
                    wx.setStorageSync("latitude", res.result.location.lat)
                    wx.setStorageSync("longitude", res.result.location.lng)
                    wx.setStorageSync("address", res.result.address)
                    that.setData({
                        cityName: res.result.address_component.city.replace("市", '')
                    })
                    that.initData()
                },
                fail: function(res) {
                    var d = new Date().getTimezoneOffset() / 60;
                    if (d == -8) {
                        that.setData({
                            country: "China"
                        })
                    } else {
                        that.setData({
                            country: "USA"
                        })
                    }
                    that.initData()
                },
                complete: function(res) {}
            });
        } else {
            this.initData()
        }

    },
    initData() {
        var that = this
        that.setData({
            isChinese: wx.getStorageSync("isChinese"),
            years: [],
            items: [],
            newCount: app.globalData.newCount
        })
        var timestamp = Date.parse(new Date());
        wx.setNavigationBarTitle({
            title: that.data.isChinese ? "万趴" : "Onepartygo"
        })
        let newDate = Format.Format()
        app.getApi.getNsProducts("POST", {
            startDate: newDate,
            cityName: that.data.cityName,
            country: that.data.country,
            method: "opg.mobile.evendatalist.find"
        }).then(data => {
            var today = newDate.substring(0, 4) + newDate.substring(5, 7) + newDate.substring(8, 10)
            var nowToday
            var years = []
            var time2 = new Date(today.substring(0, 4), parseInt(today.substring(4, 6)) - 1, today.substring(6, 8)).getTime()
            if (data.data.result && data.data.result.length > 0) {
                for (let i = 0; i < data.data.result.length; i++) {
                    var newObj = {}
                    var times = data.data.result[i].toString()
                    var ssdat = new Date(times.substring(0, 4), parseInt(times.substring(4, 6)) - 1, times.substring(6, 8))
                    var newTime = ssdat.getDay()
                    var month = Format.getMonth(parseInt(times.substring(4, 6)), that.data.isChinese)
                    var week = Format.getWeek(newTime, that.data.isChinese)
                    if (data.data.result[0] == today && i == 0) {
                        week = that.data.isChinese ? "今天" : "Today";
                    }
                    if (Math.abs(parseInt((time2 - ssdat.getTime()) / 1000 / 3600 / 24)) == 1 && (i == 0 || i == 1)) {
                        week = that.data.isChinese ? "明天" : "tmr";
                    }
                    newObj.year = times.substring(0, 4)
                    newObj.month = month
                    newObj.monthN = parseInt(times.substring(4, 6)) > 10 ? parseInt(times.substring(4, 6)) : "0" + parseInt(times.substring(4, 6))
                    newObj.day = times.substring(6, 8) //可选择的日期（天）
                    newObj.str = week //可选择的日期（周几）
                    newObj.dates = times.substring(0, 4) + times.substring(4, 6) + times.substring(6, 8) //可选择的日期
                    newObj.select = false //选中的状态
                    years.push(newObj)
                    if (String(years[0].year) + String(years[0].monthN) + String(years[0].day) == times) {
                        that.setData({
                            isNotEndNow: 1,
                            selecDate: newObj.year + "年" + newObj.month + "月" + newObj.day + "日"
                        })
                        newDate = newObj.year + "-" + newObj.monthN + "-" + newObj.day + " 00:00:00"
                    }
                    that.setData({
                        newDate: newDate
                    })

                }
                getList(that, newDate)
            } else {
                that.setData({
                    isNotEndNow: 1
                })
                getList(that, newDate)
            }

            wx.setStorageSync('years', years)
            that.setData({
                years: years
            })
        }).catch(data => {
            wx.showModal({
                title: that.data.isChinese ? "提示" : "Prompt",
                showCancel: false,
                content: "网络出错"
            })
        })

    },
    getDates() {
        let newDate = Format.Format()
        var params = {
            startDate: newDate,
            method: "opg.mobile.evendatalist.find"
        }
        app.getApi.getNsProducts("POST", params).then(res => {})
    },
    onShow() {
        // this.setData({
        //     pageNumber: 1,
        //     items: [],
        //     years: [],
        //     hidden: false,
        //     loadMore: true,
        //     isAll: false,
        //     isNotEndNow: 0,
        //     noData: false
        // })
        if (app.globalData.newCount > 0) {
            wx.setTabBarBadge({
                index: 1,
                text: app.globalData.newCount
            })
        }
        if (app.globalData.ifIndexOnshow) {

            this.setData({
                pageNumber: 1,
                items: [],
                years: [],
                hidden: false,
                loadMore: true,
                isAll: false,
                isNotEndNow: 1,
                noData: false,
                cityName: wx.getStorageSync("areaName"),
                cityId: wx.getStorageSync("areaId"),
                country: wx.getStorageSync("country")
            })
            this.initData()

            // getList(this, this.data.newDate)
            // }else{

        }

        // if (getApp().getApi.session == null || getApp().getApi.session == "") {
        //     getApp().watch = this.initData
        // } else {
        // this.initData()
        // }
    },
    onHide() {
        app.globalData.ifIndexOnshow = 0 //页面隐藏时重置首页是否选择城市的状态
    },
    onPullDownRefresh: function() {
        app.globalData.ifIndexOnshow = 1
        this.onShow()
    },
    getUserInfo: function(e) { // 获取用户信息
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    selectDate(e) { //切换活动日期
        var that = this
        let year = e.currentTarget.dataset.year,
            month = e.currentTarget.dataset.month,
            monthN = e.currentTarget.dataset.monthn,
            day = e.currentTarget.dataset.day,
            nowToday = year + "年" + month + "月" + day + "日",
            newDate = year + "-" + monthN + "-" + day + " 00:00:00";
        that.setData({
            selecDate: nowToday,
            pageNumber: 1,
            items: [],
            hidden: false,
            loadMore: true,
            isAll: false,
            isNotEndNow: 0,
            newDate: newDate
        })
        if (e.currentTarget.dataset.index == 0) {
            that.setData({
                isNotEndNow: 1
            })
        }
        getList(that, newDate)
    },
    lookImg(e) {
        let imgList = e.currentTarget.dataset.imglist
        wx.previewImage({
            current: imgList[0], // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
    },
    city() {
        wx.navigateTo({
            url: '../country/country?isTpe=1',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    detail(e) { //查看详情
        if (!toActivityDetails) {
            let id = e.currentTarget.dataset.id
            toActivityDetails = true
            wx.navigateTo({
                url: '../activityDetails/activityDetails?id=' + id,
                success: function(res) {

                },
                fail: function(res) {},
                complete: function(res) {
                    toActivityDetails = false
                },
            })
        }

    },
    onReachBottom() { //触底事件
        var that = this
        if (!that.data.isAll && !that.data.loadMore) {
            that.setData({
                pageNumber: that.data.pageNumber + 1,
                loadMore: true

            })
            getList(that)
        } else {
            that.setData({
                hidden: true
            })
        }
    },
    dateSelect() { //选择日期
        wx.navigateTo({
            url: '../dateSelect/dateSelect',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    onShareAppMessage() {
        return {
            title: this.data.isChinese ? "万趴" : "Onepartygo",
            path: '/pages/index/index',
            success: function(res) {
                // 转发成功
            },
            fail: function(res) {
                // 转发失败
            }
        }
    },
})